package com.cxb.apiDriver.interceptor;

import com.cxb.internalcommon.constant.TokenConstants;
import com.cxb.internalcommon.dto.TokenResult;
import com.cxb.internalcommon.util.JwtUtils;
import com.cxb.internalcommon.util.RedisPrefixUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean result = true;
        String resultString  = "";

        //解析token
        String token = request.getHeader("Authorization");
        TokenResult tokenResult = JwtUtils.checkToken(token);


        if(tokenResult==null ){
            resultString = "token invalid";
            result = false;
        }else{
            //从redis中取出token
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();

            String tokenKey = RedisPrefixUtils.generatorTokenKey(phone,identity, TokenConstants.ACCESS_TOKEN_TYPE);
            //从Redis中取出token
            String tokenValue = stringRedisTemplate.opsForValue().get(tokenKey);
            if((tokenValue.isEmpty()) || (!token.trim().equals(tokenValue.trim()))){
                resultString = "access token invalid";
                result = false;
            }
        }

        return result;
    }
}
